package com.charmpeach.tsss.customer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ResponseCache;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class LogManager implements LogInterface
{
	
	private static String sessionID = null;
	
	@Override
	public String login()
	{
		if(sessionID != null)
			return sessionID;
		
		return null; 
	}
	
	
	@Override
	public String login(String username, String password)
	{
		if(sessionID != null)
			return sessionID;
		
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://218.94.159.102/GlobalLogin/loginservlet");
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("username", username));
		nameValuePairs.add(new BasicNameValuePair("password", password));
		
		try
		{
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(post);
			
			if(EntityUtils.toString(response.getEntity()).contains("<p>Login Failed</p>"))
			{
				return null;
			}
			
			List<Cookie> cookies = client.getCookieStore().getCookies();
			for(Cookie cookie : cookies)
			{
				if(cookie.getName().equals("JSESSIONID"))
				{
					sessionID = cookie.getValue();
					break;
				}
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		HttpGet get = new HttpGet("http://218.94.159.102/tss/en/home/postSignin.html?SIGlobalLogin=" + sessionID);

		return sessionID;
	}
	
}
